package com.xiaotu.spider.weibo.pipeline;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Date;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.xiaotu.common.model.TVWeiBoExponentialModel;
import com.xiaotu.common.util.Constants;
import com.xiaotu.common.util.DataRedisKeyUtils;
import com.xiaotu.common.util.DateUtils;
import com.xiaotu.common.util.SepratorUtil;
import com.xiaotu.common.util.StringUtil;
import com.xiaotu.spider.APipeline;

import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;

/**
 * @类名 TVWeiBoExponentialPipeline
 * @日期 2017年12月19日
 * @作者 王艳龙
 * @功能 微博指数数据pipeline
 */
@Component("TVWeiBoExponentialPipeline")
public class TVWeiBoExponentialPipeline extends APipeline
{
	private static Logger log = Logger.getLogger(TVWeiBoExponentialPipeline.class);
	@Override
	protected void doProcess(ResultItems resultItems, Task task)
	{
		TVWeiBoExponentialModel weiboModel = resultItems.get(TVWeiBoExponentialModel.class.getName());
        if (weiboModel == null)
            return;
        String keys = getTVKey();
    	cacheHandler.hSet(keys, weiboModel.getTvId(), weiboModel.getTvName());
        cacheHandler.setCacheTimeout(keys);
        
        try{
        String filePath =resultItems.get("path");
        StringBuffer buffer = new StringBuffer();
        buffer.append(weiboModel.getWb_getchartdata()+SepratorUtil.SEP_TXT_LN).append(weiboModel.getWb_realtime1hour()+SepratorUtil.SEP_TXT_LN)
        .append(weiboModel.getWb_realtime24hour()+SepratorUtil.SEP_TXT_LN).append(weiboModel.getWb_keywordzone()+SepratorUtil.SEP_TXT_LN)
        .append(weiboModel.getWb_crowdpositioning());
        
        String path = filePath + SepratorUtil.SEP_SLASH_EN +
        		StringUtil.converterToSpell(weiboModel.getTvName())+
        		SepratorUtil.SEP_SLASH_EN+DateUtils.getDateString(
				new Date(), "yyyyMMdd") +".txt.tmp";
        PrintWriter printWriter = new PrintWriter(
        		new OutputStreamWriter(new FileOutputStream(
        				StringUtil.getFile(path)
        						),"UTF-8"));
        printWriter.println("kw="+weiboModel.getTvName());
        printWriter.println(buffer.toString());
        printWriter.close();
        Runtime.getRuntime().exec("mv "+path+" "+path.substring(0, path.lastIndexOf(".")));
        
		} catch (IOException e) {
			log.warn("write file error", e);
	    }
}
	
	protected String getTVKey()
	{
		return DataRedisKeyUtils
				.getKey(Constants.DataRedisKey.TV_WEIBO_EXPONENTIAL_YYYYMMDD);
	}

}